//
//  PlatformInterventionVC.m
//  yunbaolive
//
//  Created by ybRRR on 2020/3/23.
//  Copyright © 2020 cat. All rights reserved.
//

#import "PlatformInterventionVC.h"
#import "TZImagePickerController.h"
#import <Qiniu/QiniuSDK.h>
#import "YBStorageObj.h"
@interface PlatformInterventionVC ()<UIPickerViewDelegate,UIPickerViewDataSource,UITextViewDelegate,TZImagePickerControllerDelegate>
{
    UIScrollView *_backScroll;
    MyTextView *contentText;
    UIButton *imageBtn;
    UILabel *wordCountLb;
    UIButton *delBtn;
    NSMutableArray *imageArray;

    UIView *reasonPickBack;
    UIPickerView *reasonPicker;
    NSString *selReasonStr;
    NSString *selReasonID;
    NSArray *reasonArr;

    UILabel *selLb;
    NSInteger selRow;

    NSString *picThumbsStr;

}

@end

@implementation PlatformInterventionVC

-(void)requestReason{
    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          };
    
    [WYNetworking postWithUrl:@"Buyer.getPlatformReasonList" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            reasonArr = info;
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
     }];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleL.text = YZMsg(@"平台介入");
    imageArray = [NSMutableArray array];
    picThumbsStr = @"";
    selReasonID = @"-999999";
    self.view.backgroundColor = UIColor.whiteColor;
    self.subNavi.backgroundColor = UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
    self.naviLine.hidden = NO;
    self.naviLine.backgroundColor = RGB(245, 245, 245);
    _backScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64+statusbarHeight, _window_width, _window_height)];
    _backScroll.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:_backScroll];
    
    UILabel *titleLb = [[UILabel alloc]init];
    titleLb.frame = CGRectMake(15, 10, 80, 30);
    titleLb.font = [UIFont systemFontOfSize:14];
    titleLb.textColor = UIColor.grayColor;
    titleLb.text = YZMsg(@"申诉原因");
    [_backScroll addSubview:titleLb];
    
    UIImageView *rightImg = [[UIImageView alloc]init];
    rightImg.frame = CGRectMake(_window_width-25, 10, 15, 15);
    rightImg.image = [UIImage imageNamed:@"shop_right"];
    [_backScroll addSubview:rightImg];
    rightImg.centerY = titleLb.centerY;
    
    selLb = [[UILabel alloc]init];
    selLb.frame = CGRectMake(rightImg.left-150, 10, 145, 30);
    selLb.font = [UIFont systemFontOfSize:14];
    selLb.textColor = UIColor.grayColor;
    selLb.text = YZMsg(@"请选择");
    selLb.textAlignment = NSTextAlignmentRight;
    [_backScroll addSubview:selLb];

    UIButton *selReason = [UIButton buttonWithType:0];
    selReason.frame = CGRectMake(0, 0, _window_width, 50);
    [selReason addTarget:self action:@selector(selReason) forControlEvents:UIControlEventTouchUpInside];
    [_backScroll addSubview:selReason];
    
    UILabel *line = [[UILabel alloc]init];
    line.frame =CGRectMake(0, titleLb.bottom+10, _window_width, 8);
    line.backgroundColor = RGB(245, 245, 245);
    [_backScroll addSubview:line];

    contentText = [[MyTextView alloc]init];
    contentText.frame = CGRectMake(10, line.bottom+5, _window_width-20, 150);
    contentText.placeholderColor = [UIColor grayColor];
    contentText.placeholder =YZMsg(@"请填写详细原因与证据描述,有助于快速解决你的问题");
    contentText.font = [UIFont systemFontOfSize:14];
    contentText.delegate = self;
    contentText.textColor = [UIColor blackColor];
    contentText.backgroundColor = RGB(245, 245, 245);
    [_backScroll addSubview:contentText];
    
    imageBtn = [UIButton buttonWithType:0];
    imageBtn.frame = CGRectMake(15, contentText.bottom+5, 70, 70);
    [imageBtn setBackgroundImage:[UIImage imageNamed:getImagename(@"refund_upimg")] forState:0];
    [imageBtn addTarget:self action:@selector(uploadImage) forControlEvents:UIControlEventTouchUpInside];
    [_backScroll addSubview:imageBtn];

    delBtn = [UIButton buttonWithType:0];
    delBtn.frame = CGRectMake(imageBtn.width-25, 5, 20, 20);
    [delBtn setBackgroundImage:[UIImage imageNamed:@"comm_del"] forState:0];
    [delBtn addTarget:self action:@selector(delVideoClick) forControlEvents:UIControlEventTouchUpInside];
    [imageBtn addSubview:delBtn];
    delBtn.hidden = YES;

    wordCountLb = [[UILabel alloc]init];
    wordCountLb.frame = CGRectMake(_window_width-100, 0, 90, 20);
    wordCountLb.centerY = imageBtn.centerY;
    wordCountLb.font = [UIFont systemFontOfSize:14];
    wordCountLb.textColor = UIColor.grayColor;
    wordCountLb.text = @"0/300";
    wordCountLb.textAlignment = NSTextAlignmentRight;
    [_backScroll addSubview:wordCountLb];

    _backScroll.size = CGSizeMake(_window_width, imageBtn.bottom+10);
    
    UIButton *submitBtn = [UIButton buttonWithType:0];
    submitBtn.frame = CGRectMake(0, _window_height-40-ShowDiff, _window_width, 40);
    [submitBtn setTitle:YZMsg(@"提交申请") forState:0];
    [submitBtn setTitleColor:[UIColor whiteColor] forState:0];
    submitBtn.titleLabel.font =[UIFont systemFontOfSize:14];
    [submitBtn setBackgroundColor:Pink_Cor];
    [submitBtn addTarget:self action:@selector(submitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:submitBtn];

    [self requestReason];
}
-(void)delVideoClick{
    delBtn.hidden = YES;
    [imageArray removeAllObjects];
    [imageBtn setBackgroundImage:[UIImage imageNamed:getImagename(@"refund_upimg")] forState:0];
}

//选择图片
-(void)uploadImage{
    TZImagePickerController *imagePC = [[TZImagePickerController alloc]initWithMaxImagesCount:1-imageArray.count delegate:self];
    imagePC.preferredLanguage = [lagType isEqual:ZH_CN] ? @"zh-Hans":@"en";
    imagePC.modalPresentationStyle = 0;
    imagePC.showSelectBtn = YES;
    imagePC.allowCrop = NO;
    imagePC.allowPickingOriginalPhoto = NO;
    imagePC.oKButtonTitleColorNormal = Pink_Cor;
    imagePC.allowTakePicture = YES;
    imagePC.allowTakeVideo = NO;
    imagePC.allowPickingVideo = NO;
    imagePC.allowPickingMultipleVideo = NO;
    [[[YBBaseAppDelegate sharedAppDelegate] topViewController]presentViewController:imagePC animated:YES completion:nil];
}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    NSLog(@"------多选择图片--：%@",photos);
    [imageArray addObjectsFromArray:photos];
    [imageBtn setBackgroundImage:photos[0] forState:0];
    delBtn.hidden = NO;

}
#pragma mark------选择原因-------
-(void)selReason{
    [self.view endEditing:YES];
    if (!reasonPickBack) {
        reasonPickBack = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height)];
        reasonPickBack.backgroundColor = RGB_COLOR(@"#000000", 0.3);
        [self.view addSubview:reasonPickBack];
        
        UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, _window_height-240, _window_width, 40)];
        titleView.backgroundColor = [UIColor whiteColor];
        [reasonPickBack addSubview:titleView];
        
        [PublicObj lineViewWithFrame:CGRectMake(0, titleView.height-1, _window_width, 1) andColor:RGB(250, 250, 250) andView:titleView];
        
        UIButton *cancleBtn = [UIButton buttonWithType:0];
        cancleBtn.frame = CGRectMake(10, 0, 80, 40);
        cancleBtn.tag = 100;
        [cancleBtn setTitle:YZMsg(@"取消") forState:0];
        [cancleBtn setTitleColor:[UIColor blackColor] forState:0];
        cancleBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [cancleBtn addTarget:self action:@selector(cityCancleOrSure:) forControlEvents:UIControlEventTouchUpInside];
        [titleView addSubview:cancleBtn];
        
        UIButton *sureBtn = [UIButton buttonWithType:0];
        sureBtn.frame = CGRectMake(_window_width-90, 0, 80, 40);
        sureBtn.tag = 101;
        [sureBtn setTitle:YZMsg(@"完成") forState:0];
        [sureBtn setTitleColor:[UIColor blackColor] forState:0];
        sureBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [sureBtn addTarget:self action:@selector(cityCancleOrSure:) forControlEvents:UIControlEventTouchUpInside];
        [titleView addSubview:sureBtn];
        
        UILabel *titlelb = [[UILabel alloc]init];
        titlelb.frame = CGRectMake(_window_width/2-90, 0, 180, 40);
        titlelb.font = [UIFont systemFontOfSize:15];
        titlelb.text = YZMsg(@"退款原因");
        titlelb.textColor = [UIColor blackColor];
        [titleView addSubview:titlelb];
        
        reasonPicker = [[UIPickerView alloc]initWithFrame:CGRectMake(0, _window_height-200, _window_width, 200)];
        reasonPicker.backgroundColor = [UIColor whiteColor];
        reasonPicker.delegate = self;
        reasonPicker.dataSource = self;
        reasonPicker.showsSelectionIndicator = YES;
        [reasonPicker selectRow: 0 inComponent: 0 animated: YES];
        [reasonPickBack addSubview:reasonPicker];
    }else{
        reasonPickBack.hidden = NO;
    }
}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView*)textView {

    NSString *toBeString = textView.text;
    NSString *lang = [[[UITextInputMode activeInputModes]firstObject] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textView markedTextRange];//获取高亮部分
        UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
        //没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > 300) {
                textView.text = [toBeString substringToIndex:300];
                wordCountLb.text = [NSString stringWithFormat:@"%lu/300",textView.text.length];
            }else{
                wordCountLb.text = [NSString stringWithFormat:@"%lu/300",toBeString.length];
            }
        }else{
            //有高亮选择的字符串，则暂不对文字进行统计和限制
        }
    }else{
        // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
        if (toBeString.length > 300) {
            textView.text = [toBeString substringToIndex:300];
            wordCountLb.text = [NSString stringWithFormat:@"%lu/300",textView.text.length];
        }else{
            wordCountLb.text = [NSString stringWithFormat:@"%lu/300",toBeString.length];
        }
    }
}
- (void)cityCancleOrSure:(UIButton *)button{
    if (button.tag == 100) {
        //return;
    }else{
        selLb.text =  selReasonStr;
    }
    reasonPickBack.hidden = YES;
    
}
#pragma mark--- Picker Data Source Methods-----
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return reasonArr.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [reasonArr[row] valueForKey:@"name"];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    selReasonStr = [reasonArr[row] valueForKey:@"name"];
    selReasonID =[reasonArr[row] valueForKey:@"id"];
    selRow = row;
    [reasonPicker reloadAllComponents];
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        pickerLabel.font = [UIFont systemFontOfSize:15];
    }
    if (row == selRow) {
        pickerLabel.textColor = Normal_Color;
        selReasonStr =[reasonArr[selRow] valueForKey:@"name"];
        selReasonID =[reasonArr[row] valueForKey:@"id"];

    }
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;

}
#pragma mark------提交申请---------
-(void)submitBtnClick{
    if ([selReasonID isEqual:@"-999999"]) {
        [MBProgressHUD showPop:YZMsg(@"请选择申诉原因")];
        return;
    }
    [MBProgressHUD showMessage:@""];
    if (imageArray.count > 0) {
        YBWeakSelf;
        [[YBStorageObj storageManeger]getCOSType:^(int code) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (code == 0) {
                    [weakSelf startUploadCer];
                }
            });
        }];
    }else{
        [self uploadService];
    }

}
-(void)startUploadCer{
    [MBProgressHUD showMessage:@""];
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    YBWeakSelf;
    UIImage *image =imageArray[0];

    if (image) {
        dispatch_group_async(group, queue, ^{
            NSString *imageName = [PublicObj getNameBaseCurrentTime:@"_action_image_cover.png"];
            [[YBStorageObj storageManeger]yb_storageImg:image andName:imageName progress:^(CGFloat percent) {
                
            }complete:^(int code, NSString *key) {
                picThumbsStr = minstr(key);
                dispatch_semaphore_signal(semaphore);
            }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        });
    }
    
    dispatch_group_notify(group, queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf uploadService];
        });
        NSLog(@"任务完成执行");
    });

}

-(void)uploadService{
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken],@"orderid":self.orderIDStr,@"reasonid":selReasonID, @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"orderid":self.orderIDStr,
                          @"reasonid":selReasonID,
                          @"content":contentText.text,
                          @"thumb":picThumbsStr,
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign
                          };
    
    [WYNetworking postWithUrl:@"Buyer.applyPlatformInterpose" Dic:dic Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        if (code ==0) {
            [MBProgressHUD showError:msg];
            [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:([self.navigationController.viewControllers count] -3)] animated:YES];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            [MBProgressHUD hideHUD];

     }];

}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


@end
